<!-- 库存管理-物料管理-计量单位-多计量 -->
<template>
  <div class="container">
    <div>
      <a-space style="display: flex; justify-content: space-between">
        <a-space
          ><a-input-search
            search-button
            @search="search"
            v-model="searchName"
            placeholder="请输入库位名称"
          />
          <a-input-search
            search-button
            @search="search"
            v-model="searchNumber"
            placeholder="请输入库位编号"
          />
          <a-button type="outline" @click="reset">
            <template #icon> <icon-refresh /> </template> 重置
          </a-button></a-space
        >

        <a-button type="primary" @click="handleClick"> 新增库位</a-button>
      </a-space>
    </div>
    <a-divider />
    <tableTurn :tableData="getData" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        title="库位编码"
        data-index="number"
        align="center"
      />

      <a-table-column
        :width="150"
        title="库位名称"
        data-index="name"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      />
      <a-table-column title="库位尺寸" align="center">
        <a-table-column
          :width="80"
          title="长（d）"
          data-index="long"
          align="center"
        />
        <a-table-column
          :width="80"
          title="宽（w）"
          data-index="wide"
          align="center"
        />
        <a-table-column
          :width="80"
          title="高（h）"
          data-index="high"
          align="center"
        />
      </a-table-column>
      <a-table-column
        :width="150"
        title="所在位置"
        data-index="location"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      />

      <a-table-column
        :width="150"
        title="库位最大承重"
        data-index="weight"
        align="center"
        ><template #cell="{ record }">
          <span>{{ record.weight }}kg</span>
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        title="备注"
        data-index="remark"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      />
      <a-table-column fixed="right" :width="150" title="操作" align="center"
        ><template #cell="{ record }">
          <a-space>
            <a-tooltip content="详情">
              <IconFont
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetails(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goEdit(record)"
              />
            </a-tooltip>
            <a-tooltip content="删除">
              <a-popconfirm
                content="确认删除？"
                type="error"
                @ok="deleteItem(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </tableTurn>
    <addShelf
      v-model:visible="modalVisible"
      @addLocationForm="addLocationForm"
      :formData="UnitForm"
      :createId="createId"
      :title="titleModel"
      :isMark="isMarkMsg"
    />
    <!-- <unitAdd
      type="edit"
      v-model:visible="modalVisible"
      :form="currForm.list"
      @unitEmit="unitEmit"
    ></unitAdd> -->
  </div>
</template>

<script lang="ts" setup>
  import {
    computed,
    ref,
    reactive,
    onMounted,
    h,
    watchEffect,
    nextTick,
  } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    postLocation,
    putLocation,
    delLocation,
    GetLocationAll,
  } from '@/api/inventory-management/warehouse-management/location-list/index';
  import miiter from '@/utils/mitt';
  import { useRouter } from 'vue-router';
  import addShelf from './components/add-location.vue';

  const router = useRouter();
  const tableRef = ref();
  const formData = ref();
  const isAddMark = ref();
  // const props = withDefaults(
  //   defineProps<{
  //     getTableData: any;
  //   }>(),
  //   {}
  // );
  const searchName = ref();
  const searchNumber = ref();
  const checkTreeData = ref();
  const titleModel = ref();
  const isMarkMsg = ref(); //存储库区与货架的标识
  const createId = ref();
  const modelVisible = ref(false);
  const selectMark = ref();
  miiter.on('locationId', (val: any) => {
    createId.value = val.id;
    selectMark.value = val.mark;
    nextTick(() => {
      tableRef.value.loadData();
    });
  });

  miiter.on('checkTree', (val: any) => {
    isMarkMsg.value = val.isMark;
    checkTreeData.value = val.checkedNodes;
  });

  const UnitForm = ref();

  let modalVisible = ref(false);

  // 储存当前行的数据
  const currForm = reactive({
    list: {},
  });

  const handleClick = () => {
    const NewIds = [];
    checkTreeData.value.forEach((item) => {
      NewIds.push(item.id);
    });

    let isNorms = checkTreeData.value.every(
      (item: any) =>
        item.lattice === checkTreeData.value[0].lattice &&
        item.tier === checkTreeData.value[0].tier
    );
    let isMark = checkTreeData.value.every(
      (item: any) => item.mark === checkTreeData.value[0].mark
    );
    if (checkTreeData.value.length <= 0) Message.error('请选择货架！');
    if (!isNorms) Message.error('选择的货架规格不一致，无法批量新增！');
    if (!isMark) Message.error('货架与库区冲突，无法新增！');
    if (isNorms && isMark && checkTreeData.value.length > 0) {
      const { attribute, lattice, tier, location } = checkTreeData.value[0];
      if (isMarkMsg.value === 2) {
        UnitForm.value = {
          name: '', //库位名称
          number: '', //库位编号
          materialTypeId: undefined, //物品存放类型id
          materialId: undefined, // 指定存放物料id
          materialName: '',
          long: undefined, //长
          wide: undefined, //宽
          high: undefined, //高
          weight: undefined, // 最大承重量
          attribute,
          lattice,
          tier,
          location, //所在位置
          mark: 3, // 标识:1.仓库2.货架3.库位
          remark: '',
          state: 1,
          ids: NewIds,
        };
        modalVisible.value = true;
        titleModel.value = '新建库位';
        isAddMark.value = isMarkMsg.value;
      } else if (NewIds.length > 1) Message.error('不可以选择多个库区');
      else if (!isMarkMsg.value) Message.error('请选择库区或货架');
      else {
        UnitForm.value = {
          name: '', //库位名称
          number: '', //库位编号
          materialTypeId: undefined, //物品存放类型id
          materialId: undefined, // 指定存放物料id
          long: undefined, //长
          wide: undefined, //宽
          high: undefined, //高
          shelvesId: undefined, //所属货架id
          weight: undefined, // 最大承重量
          attribute,
          lattice,
          tier,
          location, //所在位置
          mark: 3, // 标识:1.仓库2.货架3.库位
          remark: '',
          state: 1,
          warehouseId: checkTreeData.value[0].id,
          materialName: checkTreeData.value[0].name,
        };
        modalVisible.value = true;
        titleModel.value = '新建库位';
        isAddMark.value = isMarkMsg.value;
      }
    }
  };

  const reset = () => {
    searchName.value = '';
    searchNumber.value = '';
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const addLocationForm = async (data: any) => {
    try {
      if (titleModel.value === '新建库位') {
        await postLocation({ ...data });
        tableRef.value.loadData();
      } else {
        await putLocation({ ...data });
        tableRef.value.loadData();
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const putUnit = (val) => {
    modalVisible.value = true;
    UnitForm.value = val;
  };

  // 前往编辑
  const goEdit = (record: any) => {
    titleModel.value = '修改库位';
    modalVisible.value = true;
    UnitForm.value = record;
    isMarkMsg.value = record.mark;
  };

  const deleteItem = async (id: number) => {
    try {
      await delLocation({ id });
      // router.go(0);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  const goDetails = (id) => {
    router.push({
      name: 'LocationListDetails',
      query: { id },
    });
  };

  const getData = async (page?: any) => {
    try {
      let data: any = {};
      if (searchName.value) data.name = searchName.value;
      if (searchNumber.value) data.number = searchNumber.value;
      if (selectMark.value === 2) data.shelvesId = createId.value;
      if (selectMark.value === 1 || selectMark.value === 0)
        data.warehouseId = createId.value;
      const res = GetLocationAll({
        ...page,
        ...data,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  defineExpose({ handleClick });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 0px 20px;
    margin-bottom: 20px;

    .content {
      padding: 10px 10px;
    }
    .state-item-Y {
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(148, 191, 255, 1);
      background-color: rgba(232, 243, 255, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #3d7eff;
    }
    .state-item-N {
      color: #f53f3f;
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(251, 172, 163, 1);
      background-color: rgba(255, 236, 232, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  // 扩展行的样式

  // .space-unit {
  //   background-color: var(--color-bg-2);
  //   border-radius: 4px;
  // }

  // .title-fix {
  //   margin: 0 0 12px 0;
  //   font-size: 14;
  // }
  // :deep(.section-title) {
  //   margin: 0 0 12px 0;
  //   font-size: 14px;
  // }
</style>
